(function() {

	nsbase.views.hardware = new HardwareFunc();

	function HardwareFunc() {
		var _self = this;

		_self.init = init;
		_self.appletLoad = appletLoad;

		var hardwareActions = nsbase.config.actionUrl.hardware,
			utilities = nsbase.utility,
			validations = nsbase.utility.validations,
        	clientResource = nsbase.resources.clientResource;

		var applet, networkInterface = null;

		var stationStateEnum = {idle: 1, working: 2},
			deviceStateEnum = {idle: 1, working: 2,unBind:3},
			currentState = stationStateEnum.idle;

		var cssClass = {
			failed:"failed",
			selected:"selected"
		};

		var $smartForm = $("#smartForm");
		var _config;
		function init(config) {
			_config = $.extend({},config);

      		$(".nav_menu li.Hardware").addClass(cssClass.selected);
			$("#lblStationCount").tooltip();
			initSmartFrom();
			getStationStatus();
			monitorStation();
			initSettingForm();
		}

		// 添加 java applet
		function initApplet (container) {
			if(container.find("applet").length==0){
				container.append("<applet archive='../static/scripts/views/hardware/smartConfig.jar' code='SmartConfig.class' width='1' height='1'></applet>");
			}
		}
		function initSmartFrom () {
			var	$txtSSID = $smartForm.find(".txtSSID"),
				$txtPwd = $smartForm.find(".txtPwd"),
				$txtGateway = $smartForm.find(".txtGateway"),
				$btnConfig = $smartForm.find("#btnConfigStation");

			$("#btnAddStation").click(function(){
				var sender = $(this);
				var $container = sender.parents(".step:first");
				$container.find(".op_wrap").animate({marginTop:-170});

				initApplet($smartForm);
			});

			$("#btnEditStation").click(function () {
				var sender = $(this);
				var $container = sender.parents(".step:first");
				$container.find(".operate_form").animate({marginTop:0});

				initApplet($smartForm);
			});
			$smartForm.find("input").blur(function(){
				inputEmptyValidate([$(this)]);
			});
			$txtGateway.blur(function () {
				var sender = $(this);
				var labelDesc = utilities.trimEnd(sender.prev().text(),'：');
				sender.removeClass(cssClass.failed);
				sender.tooltip();
				if (!validations.ipValidate(utilities.trim(sender.val()))){
					sender.addClass(cssClass.failed).attr("title",utilities.stringFormat(clientResource.msgGatewayIp, labelDesc));
				} else{
					sender.tooltip("destroy");
				}
			});

			$btnConfig.click(function(){
				var sender = $(this);
				var intervalId;
				if(!applet){
					utilities.errorDialog(clientResource.msgJavaNoWork);
					return;
				}
				inputEmptyValidate([$txtSSID,$txtPwd,$txtGateway]);
				if($smartForm.find("."+cssClass.failed).length >0){
					return;
				}

				var ssid = $txtSSID.val(),
					password = $txtPwd.val(),
					gateway = $txtGateway.val();
				if(currentState == stationStateEnum.idle){
					currentState = stationStateEnum.working;
					sender.text(clientResource.btnStopConfig);
					if(networkInterface)
						applet.startTransmitting(networkInterface, ssid, gateway, password, "smartconfigAES16", "CC3000");//encryptionKey, ackString
					// 30秒一次检查配置station 状态
					intervalId = setInterval(getStationStatus,1000*30,function(){
						if(currentState == stationStateEnum.working){
							clearInterval(intervalId);
							sender.text(clientResource.btnConfig);
							//currentState = stationStateEnum.idle;
							if(networkInterface)
								applet.stopTransmitting();
						}
					});
				} else if(currentState == stationStateEnum.working){
					sender.text(clientResource.btnConfig);
					clearInterval(intervalId);
					if(networkInterface)
						applet.stopTransmitting();
					//currentState = stationStateEnum.idle;
				}
			});

			$("#btnRefresh").click(function(event) {
				getStationStatus();
			});
		}

		function initSettingForm () {
			var $settingTime = $("#settingTime"),
				$txtDeviceId = $("#txtDeviceId"),
				$rdUpload = $("#rdUpload"),
				$rdSleep = $("#rdSleep"),
				$btnConfirm = $("#btnConfirm"),
				$btnRevert = $("#btnRevert"),
				$uploadTimeContainer = $settingTime.find(".upload_time"),
				$sleepTimeContainer = $settingTime.find(".sleep_time"),
				$selectHour = $settingTime.find(".hour"),
				$selectMinute = $settingTime.find(".minute");
			// init select options
			for (var i = 0; i < 24; i++) {
				if(i<10){
					$selectHour.append('<option value="'+i+'">0'+i+'</option>');
				} else {
					$selectHour.append('<option value="'+i+'">'+i+'</option>');
				}
			}

			for (var i = 0; i < 60; i++) {
				if(i<10){
					$selectMinute.append('<option value="'+i+'">0'+i+'</option>');
				} else {
					$selectMinute.append('<option value="'+i+'">'+i+'</option>');
				}
			}
			// bind defalut select value
			var uploadTime = _config.uploadTime.split(":"),
				sleepStartTime = _config.sleepStartTime.split(":"),
				sleepEndTime = _config.sleepEndTime.split(":");
			$uploadTimeContainer.find(".hour").val(uploadTime[0]);
			$uploadTimeContainer.find(".minute").val(uploadTime[1]);
			$sleepTimeContainer.find(".hour.start").val(sleepStartTime[0]);
			$sleepTimeContainer.find(".minute.start").val(sleepStartTime[1]);
			$sleepTimeContainer.find(".hour.end").val(sleepEndTime[0]);
			$sleepTimeContainer.find(".minute.end").val(sleepEndTime[1]);

			if(_config.deviceId == ""){// 设备未绑定
				bindStep2State(deviceStateEnum.unBind);
			} else if(currentState == stationStateEnum.working){
				bindStep2State(deviceStateEnum.working);
			} else {
				bindStep2State(deviceStateEnum.idle);
			}

			$("#btnAddGo,#btnGetDevice").click(function(){
				var sender = $(this);
				var $container = sender.parents(".step:first"),
					$bindGoForm = $container.find(".operate_form");
				$container.find(".op_wrap").animate({marginTop:-170},function(){
					$bindGoForm.mask();
					nsbase.ajax.request(hardwareActions.getDeviceId,null,function(result){
						$bindGoForm.unmask();
						if(result.success){
							$txtDeviceId.val(result.data);
						} else {
							utilities.errorDialog(result.message);
						}
					},function () {
						$bindGoForm.unmask();
					});
				});
			});
			
			$("#btnBindGo").click(function(){
				var sender = $(this);
				var $container = sender.parents(".step:first"),
					$bindGoForm = $container.find(".operate_form"),
					$state = $container.find(".state");
				var deviceId = utilities.trim($txtDeviceId.val());
				var labelDesc = utilities.trimEnd($txtDeviceId.prev().text(),'：');
				var regex = /^a[A-Z0-9]{5}$/;

				$txtDeviceId.removeClass(cssClass.failed);
				$txtDeviceId.tooltip();
				if (validations.isNullOrWhiteSpace(deviceId)) {
					$txtDeviceId.addClass(cssClass.failed).attr("title",utilities.stringFormat(clientResource.msgNoEmpty, labelDesc));
				} else if(!regex.test(deviceId)){
					$txtDeviceId.addClass(cssClass.failed).attr("title",utilities.stringFormat(clientResource.msgNoValid, labelDesc));
				} else {
					$txtDeviceId.tooltip("destroy");
				}
				
				if($bindGoForm.find("."+cssClass.failed).length > 0){
					return;
				}
				$bindGoForm.mask();
				var param = {
					deviceId:deviceId
				};
				nsbase.ajax.request(hardwareActions.bindDevice,param,function (result) {
					$bindGoForm.unmask();
					if(result.success){
						_config.deviceId = param.deviceId;
						if(currentState == stationStateEnum.working){
							bindStep2State(deviceStateEnum.working);
						} else {
							bindStep2State(deviceStateEnum.idle);
						}
						$rdUpload.click();
					} else {
						bindStep2State(deviceStateEnum.unBind);
						utilities.errorDialog(result.message);
					}
				},function () {
					bindStep2State(deviceStateEnum.unBind);
					$bindGoForm.unmask();
				});
				
			});

			$("#btnUnBind").click(function() {
				var sender = $(this);
				var $container = sender.parents(".step:first"),
					$bindGoForm = $container.find(".operate_form");
				var param = {
					deviceId:_config.deviceId
				};

				nsbase.ajax.request(hardwareActions.unbindDevice,param,function (result) {
					$bindGoForm.unmask();
					if(result.success){
						_config.deviceId = "";
						bindStep2State(deviceStateEnum.unBind);
						$rdUpload.click();
					} else {
						utilities.errorDialog(result.message);
					}
				},function () {
					$bindGoForm.unmask();
				});

			});
			$rdUpload.click(function () {
				$sleepTimeContainer.hide();
				$uploadTimeContainer.show();
			});

			$rdSleep.click(function () {
				$uploadTimeContainer.hide();
				$sleepTimeContainer.show();
			});

			$btnConfirm.click(function () {
				if($rdSleep.prop("checked")){
					setSleepTime($settingTime);
				}
				if($rdUpload.prop("checked")){
					setUploadTime($settingTime);
				}
			});

			$btnRevert.click(function () {
				if($rdSleep.prop("checked")){
					resetSleepTime($settingTime);
				}
				if($rdUpload.prop("checked")){
					resetUploadTime($settingTime);
				}
			});

			$rdUpload.click();
		}

		function setUploadTime (container) {
			container.mask();
			var hourValue = container.find(".upload_time .hour").val(),
				minuteValue = container.find(".upload_time .minute").val();
			var param = {
				uploadTime:hourValue+":"+minuteValue
			};
			nsbase.ajax.request(hardwareActions.setUploadTime,param,function (result) {
				container.unmask();
				if(result.success){
					// 绑定自动上传时间成功后，同步变量值
					_config.uploadTime = param.upload_time;

				} else{
					utilities.errorDialog(result.message);
				}
			},function () {
				container.unmask();
			});
		}
		function setSleepTime (container) {
			container.mask();
			var startHhour = container.find(".sleep_time .hour.start").val(),
				startMinute = container.find(".sleep_time .minute.start").val();
				endHhour = container.find(".sleep_time .hour.end").val(),
				endMinute = container.find(".sleep_time .minute.end").val();
			var param = {
				startTime:startHhour+":"+startMinute,
				endTime:endHhour+":"+endMinute
			};
			nsbase.ajax.request(hardwareActions.setSleepTime,param,function (result) {
				container.unmask();
				if(result.success){
					// 绑定睡眠时间成功后，同步变量值
					_config.sleepStartTime = param.start_time;
					_config.sleepEndTime = param.end_time;
				} else{
					utilities.errorDialog(result.message);
				}
			},function () {
				container.unmask();
			});
		}

		function resetUploadTime (container) {
			var uploadTime = _config.uploadTime.split(":");
			container.find(".upload_time .hour").val(uploadTime[0]);
			container.find(".upload_time .minute").val(uploadTime[1]);
		}
		function resetSleepTime (container) {
			var sleepStartTime = _config.sleepStartTime.split(":"),
				sleepEndTime = _config.sleepEndTime.split(":");
			container.find(".sleep_time .hour.start").val(sleepStartTime[0]);
			container.find(".sleep_time .minute.start").val(sleepStartTime[1]);
			container.find(".sleep_time .hour.end").val(sleepEndTime[0]);
			container.find(".sleep_time .minute.end").val(sleepEndTime[1]);
		}

		function inputEmptyValidate(inputs) {
			$.each(inputs, function(i, item) {
				var labelDesc = utilities.trimEnd(item.prev().text(),'：');
				item.removeClass(cssClass.failed);
				item.tooltip();
				if (validations.isNullOrWhiteSpace(item.val())) {
					item.addClass(cssClass.failed).attr("title",utilities.stringFormat(clientResource.msgNoEmpty, labelDesc));
				} else {
					item.tooltip("destroy");
				}
			});
		}

		// load java applet
		function appletLoad(){
			applet = document.applets[0];
			browser = window.navigator.appName
			$smartForm.mask();
			if (!((browser== "Microsoft Internet Explorer")||(browser == "Netscape"))){
				utilities.errorDialog(clientResource.msgSuggestExplorer);
			}
			if(applet.getNetworkParameter){
				networkInterface = applet.getNetworkParameter("interfaceName", "");
			}
				
			
			if (!networkInterface){
				$smartForm.unmask();
				utilities.errorDialog(clientResource.msgNotNetWorkParam);
				return;
			} 


			var ssid = applet.getNetworkParameter("SSID", networkInterface);
			var gatewayIpAddress = applet.getNetworkParameter("gateway", networkInterface);
			var mtu = parseInt(applet.getNetworkParameter("MTU", networkInterface));
			var is5GHz = eval (applet.getNetworkParameter("5GHz", networkInterface));
			
			$smartForm.find(".txtSSID").val(ssid);	
			$smartForm.find(".txtGateway").val(gatewayIpAddress);
			
			$smartForm.unmask();
			if (mtu < 1500){
				utilities.errorDialog(utilities.stringFormat(clientResource.msgMTUSLimit,networkInterface));
				return;
			}
			
			if (is5GHz){
				utilities.errorDialog(clientResource.msgNetworkSupport);
				return;
			}
		}

		// get et station state 
		function getStationStatus (successhandler) {
			nsbase.ajax.request(hardwareActions.getStationStatus,null,function(result){
				if(result.success){
					currentState = parseInt(result.data);
					bindStep1State(currentState);

					if(_config.deviceId == ""){//未绑定P
						bindStep2State(deviceStateEnum.unBind);
					} else if(currentState == stationStateEnum.working){
						bindStep2State(deviceStateEnum.working);
					} else {
						bindStep2State(deviceStateEnum.idle);
					}

					if(successhandler){
						successhandler();
					}
				} else {
					bindStep1State(stationStateEnum.idle);
					if(_config.deviceId == ""){//未绑定P
						bindStep2State(deviceStateEnum.unBind);
					} else{
						bindStep2State(deviceStateEnum.idle);
					}
				}
			},function () {
				currentState = stationStateEnum.idle;
			});
		}

		function bindStep1State (state) {
			var $stepContainer = $(".step1"),
				//$stepForm = $stepContainer.find(".operate_form"),
				$state = $stepContainer.find(".state");
				if(state == stationStateEnum.working){
					$stepContainer.find(".op_wrap").css("margin-top","-170px");
					//$stepForm.css("margin-top","-170px");
					if($state.length > 0 && !$state.hasClass("working")){
						$state.addClass("working");
					}
				} else {
					$stepContainer.find(".op_wrap").css("margin-top",0);
					//$stepForm.css({marginTop:0});
					if($state.length > 0 && $state.hasClass("working")){
						$state.removeClass("working");
					}
				}
				
		}
		function bindStep2State (state) {
			var $stepContainer = $(".step2"),
				$stepForm = $stepContainer.find(".operate_form"),
				$state = $stepContainer.find(".state"),
				$currentDeviceId = $("#currentDeviceId");

			if(state == deviceStateEnum.unBind){
				$stepForm.css({marginTop:0});
				if($state.length > 0 && $state.hasClass("working")){
					$currentDeviceId.empty();
					$state.removeClass("working");
				}
			} else if(state == deviceStateEnum.working){
				$stepContainer.find(".op_wrap").css("margin-top","-170px");
				$stepForm.css("margin-top","-170px");
				if($state.length > 0 && !$state.hasClass("working")){
					$currentDeviceId.text(_config.deviceId);
					$state.addClass("working");
				}
			} else {
				$stepContainer.find(".op_wrap").css("margin-top","-170px");
				$stepForm.css("margin-top","-170px");
				if($state.length > 0 && $state.hasClass("working")){
					$state.removeClass("working");
				}
			}
		}


		// get et station state per 3 minute
		function monitorStation () {
			setInterval(getStationStatus,1000*60*3);
		}
	}
})();